﻿using System;
using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;

namespace Cubicle.Core.Processors.Construct
{
    [Export("Cubicle.Processors.Construct.ValueConstructProcessor", typeof(IProcessor<InstructionRequest>))]
    [ExportMetadata("Name", "ValueConstructProcessor")]
    [ExportMetadata("Description", "Creates a value type. Valid aliases are: " + 
        "bool, byte, uint8, sbyte, int8, char, decimal, double, float, single, int, int32, uint, " + 
        "uint32, long, int64, ulong, uint64, short, int16, short, uint16, string, " +
        "system.boolean, system.byte, system.sbyte, system.char, system.decimal, system.double, system.single, " + 
        "system.int32, system.uint32, system.int64, system.uint64, system.int16, system.uint16, system.string")]
    public class ValueConstructProcessor : InstructionRequestProcessor
    {

        #region Overrides of Processor<InstructionRequest>

        public ValueConstructProcessor() : base(RequestType.CustomConstruct) { }

        public override bool Condition(InstructionRequest request)
        {
            return base.Condition(request) 
                && (request.TargetType.IsValueType 
                   || request.TargetType == typeof(string) 
                   || request.TargetType == typeof(object))  ;
        }

        public override InstructionRequest ConditionalProcess(InstructionRequest request)
        {
            var parameters = request.Inst.Parameters;
            var parameter = parameters == null || parameters.Length == 0 
                                ? null 
                                : parameters[0];
            var result = Convert.ChangeType(parameter, request.TargetType);
            request.Complete(result);
            return request;
        }

        #endregion
    }
}